package com.itheima.stock.task.impl;

import com.google.common.collect.Lists;
import com.itheima.stock.domain.StockInfoConfig;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.pojo.StockBlockRtInfo;
import com.itheima.stock.pojo.StockBusiness;
import com.itheima.stock.pojo.StockMarketIndexInfo;
import com.itheima.stock.pojo.StockRtInfo;
import com.itheima.stock.task.StockTimerTaskService;
import com.itheima.stock.utils.DateTimeUtil;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.utils.ParserStockInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class StockTimerTaskServiceImpl implements StockTimerTaskService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StockInfoConfig stockInfoConfig;
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    /**
     *
     * 国内大盘信息
     */
    @Override
    public void getInnerMarkInfo() {
        //1.定义接口
        String url=stockInfoConfig.getMarketurl()+String.join(",",stockInfoConfig.getInner());
        //2.组装请求头
        //2.1 组装请求头
        HttpHeaders headers = new HttpHeaders();
        //必须填写，否则数据采集不到

        headers.add("Referer","https://finance.sina.com.cn/stock/");
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");

        //2.2组装请求对象
        HttpEntity<Object> entity = new HttpEntity<>(headers);

        String responseInfos = restTemplate.postForObject(url, entity, String.class);

        //3数据分析
        String reg="var hq_str_(.+)=\"(.+)\";";

        Pattern pattern = Pattern.compile(reg);

        Matcher matcher = pattern.matcher(responseInfos);

        ArrayList<StockMarketIndexInfo> list = new ArrayList<>();

        while(matcher.find()){
            String marketCode = matcher.group(1);

            String otherInfo = matcher.group(2);

            String[] splitArr = otherInfo.split(",");

            String marketName=splitArr[0];
            //获取当前大盘的点数
            BigDecimal openPoint=new BigDecimal(splitArr[1]);
            //获取大盘的涨跌值
            BigDecimal preClosePoint=new BigDecimal(splitArr[2]);
            //获取大盘的涨幅
            BigDecimal curPoint=new BigDecimal(splitArr[3]);
            //获取大盘最高点
            BigDecimal maxPoint=new BigDecimal(splitArr[4]);
            //获取大盘的涨幅
            BigDecimal minPoint=new BigDecimal(splitArr[5]);
            //获取成交量
            Long tradeAmt=Long.valueOf(splitArr[8]);
            //获取成交金额
            BigDecimal tradeVol=new BigDecimal(splitArr[9]);
            //时间
            Date curTime = DateTimeUtil.getDateTimeWithoutSecond(splitArr[30] + " " + splitArr[31]).toDate();
            StockMarketIndexInfo info = StockMarketIndexInfo.builder().id(idWorker.nextId() + "").marketCode(marketCode)
                    .marketName(marketName)
                    .curPoint(curPoint)
                    .openPoint(openPoint)
                    .preClosePoint(preClosePoint)
                    .maxPoint(maxPoint)
                    .minPoint(minPoint)
                    .tradeVolume(tradeVol)
                    .tradeAmount(tradeAmt)
                    .curTime(curTime).build();

            list.add(info);

        }
        log.info("采集的当前大盘数据：{}",list);

        if(CollectionUtils.isEmpty(list)){
            log.info("未查询到！！！");
            return;
        }
        int count=stockMarketIndexInfoMapper.insertBatch(list);

        log.info("批插入了：{}条数据",count);
    }

    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;


    @Autowired
    private StockBusinessMapper stockBusinessMapper;
    /**
     * 国内板块描述


     */
    @Override
    public void getInnerEveryStockInfos() {
        List<StockBusiness> all = stockBusinessMapper.getAll();
        List<String> AllStockCode=new ArrayList<>();
        for (StockBusiness s : all) {
            AllStockCode.add(s.getSecCode().startsWith("6")?("sh"+s.getSecCode()):("sz"+s.getSecCode()));

        }

        //取到股票代码

    //    String url=stockInfoConfig.getMarketurl()+stockInfoConfig.getMarketurl()+String.join(",",stockInfoConfig.getInner());
       //  url=stockInfoConfig.getMarketurl()+stockInfoConfig.getMarketurl()+String.join(",",AllStockCode);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Referer","https://finance.sina.com.cn/stock/");
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
        HttpEntity<String> entity = new HttpEntity<>(headers);
        Lists.partition(AllStockCode,15).forEach(list->{

            threadPoolTaskExecutor.execute(()->{
            String url=stockInfoConfig.getMarketurl()+String.join(",",list);
            String result = restTemplate.postForObject(url, entity, String.class);
            String reg="var hq_str_(.+)=\"(.+)\";";

            Pattern pattern = Pattern.compile(reg);

            Matcher matcher = pattern.matcher(result);
            ArrayList<StockRtInfo> infos = new ArrayList<>();

            while(matcher.find()) {
               String marketCode = matcher.group(1);

               String stockCode = marketCode.substring(2);

               String otherInfo = matcher.group(2);

               String[] others = otherInfo.split(",");

               //大盘名称
               String stockName = others[0];
               //今日开盘价
               BigDecimal openPrice = new BigDecimal(others[1]);
               //昨日收盘价
               BigDecimal preClosePrice = new BigDecimal(others[2]);
               //当前价格
               BigDecimal currentPrice = new BigDecimal(others[3]);
               //今日最高价额
               BigDecimal maxPrice = new BigDecimal(others[4]);
               //今日最低价额
               BigDecimal minPrice = new BigDecimal(others[5]);
               //成交量
               BigDecimal tradeAmount = new BigDecimal(others[8]);
               //成交金额
               BigDecimal tradeVol = new BigDecimal(others[9]);
               //当前日期
               Date curDateTime = DateTimeUtil.getDateTimeWithoutSecond(others[30] + " " + others[31]).toDate();
               //Date currentTime = DateTime.parse(others[30] + " " + others[31], DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
               StockRtInfo stockRtInfo =StockRtInfo.builder()
                       .id(idWorker.nextId()+"")
                       .stockCode(stockCode)
                       .stockName(stockName)
                       .openPrice(openPrice)
                       .preClosePrice(preClosePrice)
                       .curPrice(currentPrice)
                       .maxPrice(maxPrice)
                       .minPrice(minPrice)
                       .tradeAmount(tradeAmount)
                       .tradeVolume(tradeVol)
                       .curTime(curDateTime)
                       .build();

             infos.add(stockRtInfo);


           }

            log.info("采集的当前大盘数据：{}",infos);

            if(CollectionUtils.isEmpty(infos)){
                log.info("未查询到！！！");
                return;
            }

            int i = stockRtInfoMapper.insertBatch(infos);
            System.out.println(i);


           });
        });

    }


    @Autowired
    private ParserStockInfoUtil parserStockInfoUtil;
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;

    /**
     * 板块实时数据采集批量插入
     */
    @Override
    public void getStockBlockInfos() {
        String url=stockInfoConfig.getBlockUrl();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Referer","https://finance.sina.com.cn/stock/");
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0");
        HttpEntity<String> entity = new HttpEntity<>(headers);
        String result = restTemplate.getForObject(url,  String.class);

        String s = result.split("\\{")[1].split("\\}")[0];
        String s1 = s.substring(0, s.length() - 1);
        String[] tmp1 = s1.split("\",\"");

        ArrayList<String> tmp2 = new ArrayList<>();
        for (String s2 : tmp1) {

            String s3 = s2.split(":")[1];
            tmp2.add(s3);

        }

        //tmp2拿到了所有的对象

        Lists.partition(tmp2,15).forEach(list-> {
            threadPoolTaskExecutor.execute(()->{
            ArrayList<StockBlockRtInfo> Infos = new ArrayList<>();
                    for (String s2 : list) {
                        String[] split = s2.split(",");
                        String label = split[0].substring(1);
                        String blockName = split[1];
                        Integer companyNum = Integer.valueOf(split[2]);
                        BigDecimal avgPrice = new BigDecimal(split[3]);
                        BigDecimal updownRate = new BigDecimal(split[5]);
                        Long tradeAmount = Long.valueOf(split[6]);
                        BigDecimal tradeVolume = new BigDecimal(split[7]);
                        Date cur_time = DateTimeUtil.getLastDate4Stock(new DateTime()).toDate();

                        StockBlockRtInfo rtInfo = StockBlockRtInfo.builder()
                                .id(idWorker.nextId() + "")
                                .label(label)
                                .blockName(blockName)
                                .companyNum(companyNum)
                                .avgPrice(avgPrice)
                                .updownRate(updownRate)
                                .tradeAmount(tradeAmount)
                                .tradeVolume(tradeVolume)
                                .curTime(cur_time)
                                .build();


                        Infos.add(rtInfo);
                    }

            int i = stockBlockRtInfoMapper.insertBatch(Infos);
            System.out.println(i);
        log.info("采集的当前大盘数据{}条",i);

        if(CollectionUtils.isEmpty(Infos)){
            log.info("未查询到！！！");
            return;
    }


              });
        });





//        String reg="var hq_str_(.+)=\"(.+)\";";
//         reg="var S_Finance_bankuai_sinaindustry = {(.+)}";
//
//        Pattern pattern = Pattern.compile(reg);
//
//        Matcher matcher = pattern.matcher(result);
//        ArrayList<StockRtInfo> infos = new ArrayList<>();
//

    }
}
